<template>
  <el-card style="width: 100%">
    <template #header>
      <CardHeader
        :title="'核心数据'"
        :tabs="[
          { label: '今日', value: 'today' },
          { label: '近7日', value: 'week' },
        ]"
        :activeTab="card1Tab"
        @tab-change="handleCard1TabChange"
      />
    </template>
    <div class="TabModel">
      <TabModel :selectedTab="selectedTab" @tab-change="handleTabModelChange" />
    </div>
    <div class="echart-content">
      <div id="line-chart" style="width: 100%; height: 212px"></div>
      <div class="shu-line"></div>
      <div class="echart-grid">
        <div class="echart-grid-row">
          <div class="echart-grid-item">
            <div class="echart-grid-item-title">
              <img
                src="https://lanhu-oss-2537-2.lanhuapp.com/SketchPngc5961fd693e745d4afffeb0607b0b9f503807cb832e4d8f3ab5cba322b9dfc36?noCache=true"
                alt="粉丝量"
              />
              粉丝量
            </div>
            <div class="echart-grid-item-data">1198</div>
            <div class="echart-grid-item-yesterday">
              同比昨天 <span class="trend-up">▲ 20</span>
            </div>
          </div>
          <div class="divider"></div>
          <div class="echart-grid-item">
            <div class="echart-grid-item-title">
              <img
                src="https://lanhu-oss-2537-2.lanhuapp.com/SketchPng3aeb224367d8b2a16d1247c114ea093b9c9c60a6b228badc1fd19e526d897353?noCache=true"
                alt="播放量"
              />
              播放量
            </div>
            <div class="echart-grid-item-data">98</div>
            <div class="echart-grid-item-yesterday">
              同比昨天 <span class="trend-down">▼ 20</span>
            </div>
          </div>
        </div>
        <div class="echart-grid-row">
          <div class="echart-grid-item">
            <div class="echart-grid-item-title">
              <img
                src="https://lanhu-oss-2537-2.lanhuapp.com/SketchPng81fd1a6069295305f2ff2bcbddec5bad9ba88f62e7bfa56093d56088566bebcc?noCache=true"
                alt="喜欢"
              />
              喜欢
            </div>
            <div class="echart-grid-item-data"><span>¥</span>2122</div>
            <div class="echart-grid-item-yesterday">
              同比昨天 <span class="trend-up">▲ 20</span>
            </div>
          </div>
          <div class="divider"></div>
          <div class="echart-grid-item">
            <div class="echart-grid-item-title">
              <img
                src="https://lanhu-oss-2537-2.lanhuapp.com/SketchPng1c6efa9d2a20041437330faa896d73ada514f1d5d509c1b46d01f15ca0c9f803?noCache=true"
                alt="评论"
              />
              评论
            </div>
            <div class="echart-grid-item-data"><span>¥</span>2122</div>
            <div class="echart-grid-item-yesterday">
              同比昨天 <span class="trend-down">▼ 20</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
  <!-- 其他卡片保持不变 -->
  <el-card style="width: 100%">
    <template #header>
      <CardHeader
        :title="'数据大盘'"
        :tabs="[
          { label: '今日对比昨日', value: 'today' },
          { label: '近14日', value: '2week' },
          { label: '近30日', value: '30week' },
        ]"
        :activeTab="card2Tab"
        @tab-change="handleCard2TabChange"
      />
    </template>
    <div class="TabModel">
      <TabModel
        :selectedTab="selectedTab1"
        @tab-change="handleTabModelChange1"
      />
    </div>
    <div class="TabComponent">
      <TabComponent
        :tabs="tabsData"
        :activeTab="activeTab"
        @tab-change="handleTabChange"
      />
    </div>
    <div class="echart-content">
      <div id="line-chart-two" style="width: 100%; height: 212px"></div>
      <div class="shu-line-261"></div>
      <div
        class="echart-chart-bing"
        id="pie-chart"
        style="width: 466px; height: 258px"
      ></div>
    </div>
  </el-card>
  <div>
    <DataCard />
  </div>
  <el-card style="width: 100%">
    <template #header>
      <CardHeader :title="'作品数据'" :showRightMore="true" />
    </template>
    <div>
      <VideoStats />
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from "vue"
import CardHeader from "@/components/CardHeader.vue"
import TabModel from "@/components/tab-model.vue"
import DataCard from "@/components/DataCard.vue"
import VideoStats from "@/components/VideoStats.vue"
import TabComponent from "@/components/TabComponent.vue"
import { ElMessage } from "element-plus"
import * as echarts from "echarts"

const card1Tab = ref("today")
const card2Tab = ref("today")
const selectedTab = ref("more-model")
const selectedTab1 = ref("more-model")
const activeTab = ref("fansTotal")
const tabsData = [
  { label: "粉丝总量", value: "fansTotal" },
  { label: "播放量", value: "playCount" },
  { label: "喜欢", value: "likes" },
  { label: "评论", value: "comments" },
]
const handleTabChange = (newTab) => {
  activeTab.value = newTab
  console.log("当前选中的选项卡:", newTab)
  // 在这里可以添加切换选项卡后的其他业务逻辑
}
const handleCard1TabChange = (v) => {
  console.log(v, "999999999")
  card1Tab.value = v
}
const handleCard2TabChange = (v) => {
  card2Tab.value = v
}

const handleTabModelChange = (v) => {
  selectedTab.value = v
}
const handleTabModelChange1 = (v) => {
  selectedTab1.value = v
}

let myChart: echarts.ECharts | null = null
let myChart1: echarts.ECharts | null = null
let myPieChart: echarts.ECharts | null = null
let resizeTimer: ReturnType<typeof setTimeout> | null = null // 用于存储定时器ID
onMounted(() => {
  myChart = echarts.init(document.getElementById("line-chart"))
  myChart1 = echarts.init(document.getElementById("line-chart-two"))
  myPieChart = echarts.init(document.getElementById("pie-chart"))
  const xAxisData = [
    "00:00",
    "04:00",
    "8:00",
    "12:00",
    "16:00",
    "20:00",
    "24:00",
  ]

  const option = {
    animation: true,
    animationDuration: 1000, // 动画持续时间（毫秒）
    animationEasing: "cubicOut", // 动画缓动效果
    // 添加 grid 配置来控制图表的边距
    grid: {
      left: "0%", // 左边距，可根据需要调整
      right: "0%", // 右边距
      top: "9%", // 上边距
      bottom: "0%", // 下边距
      containLabel: true, // 确保坐标轴标签不会被截断
    },
    tooltip: {
      trigger: "item", // 触发类型：单个数据项
      backgroundColor: "rgba(255, 255, 255, 0.95)",
      borderColor: "#ddd",
      borderWidth: 1,
      padding: 10,
      textStyle: {
        color: "#333",
        fontSize: 12,
      },
      // 自定义格式化函数（简化版）
      formatter: (param: any) => {
        return `
        <div style="color: rgba(0,0,0,0.45);">01-08</div>
        <div style="display: flex; align-items: center;">
          <img style="width: 10px;height: 10px;margin-right: 5px;" src="${
            param.seriesName === "播放量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng72e7d0ebee61604d7ed1d8269b2c7f202874f0be208ea3d42681a4cd0027af81?noCache=true"
              : param.seriesName === "粉丝量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPngc5961fd693e745d4afffeb0607b0b9f503807cb832e4d8f3ab5cba322b9dfc36?noCache=true"
              : param.seriesName === "评论量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng1c6efa9d2a20041437330faa896d73ada514f1d5d509c1b46d01f15ca0c9f803?noCache=true"
              : "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng81fd1a6069295305f2ff2bcbddec5bad9ba88f62e7bfa56093d56088566bebcc?noCache=true"
          }" />
          <span style="color: rgba(0,0,0,0.45);">${
            param.seriesName
          } <span style="margin-left: 33px;color:#000000;">${
          param.value
        }</span></span>
        </div>
      `
      },
      transitionDuration: 0.2,
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        color: "rgba(0,0,0,0.45)", // 字体颜色
        fontSize: 12, // 字体大小
        fontFamily: "PingFangSC, PingFang SC", // 字体族
        fontWeight: "normal", // 字体粗细
        interval: "auto", // 标签显示间隔
        // 自定义格式化函数（可选）
        formatter: (value: string, index: number) => {
          // 可以在这里自定义标签显示格式
          return value
        },
      },
      axisLine: {
        show: true, // 是否显示轴线
        lineStyle: {
          color: "rgba(0,0,0,0.15)", // 轴线颜色
          width: 1, // 轴线宽度
          type: "solid", // 轴线样式：solid, dashed, dotted
        },
      },
    },
    yAxis: {
      type: "value",
      color: "#000000", // 字体颜色
      fontSize: 12, // 字体大小
      fontFamily: "PingFangSC, PingFang SC", // 字体族
      fontWeight: "normal", // 字体粗细
      // 自定义格式化函数（可选）
      formatter: (value: number) => {
        if (value >= 1000) {
          return value / 1000 + "k" // 以千为单位显示
        }
        return value.toString()
      },
      // splitLine: {
      //   show: true, // 是否显示网格线
      //   lineStyle: {
      //     color: "#ffffff", // 网格线颜色
      //     width: 1, // 网格线宽度
      //     type: "solid", // 网格线样式：solid, dashed, dotted
      //   },
      // },
    },
    series: [
      {
        name: "播放量",
        type: "line",
        data: ["56", "12000", "9000", "6000", "8000", "5000", "3000"],
        itemStyle: {
          color: "#A43AFF",
        },
        lineStyle: {
          color: "#A43AFF",
        },
        animationDelay: (idx: number) => idx * 100,
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
      {
        name: "评论量",
        type: "line",
        data: ["900", "1000", "5000", "6500", "3000", "20", "900"],
        itemStyle: {
          color: "#FFD33A",
        },
        lineStyle: {
          color: "#FFD33A",
        },
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
      {
        name: "粉丝量",
        type: "line",
        data: ["0", "1100", "1300", "6070", "2000", "660", "11000"],
        itemStyle: {
          color: "#2D84FF",
        },
        lineStyle: {
          color: "#2D84FF",
        },
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
      {
        name: "喜欢",
        type: "line",
        data: ["5000", "1200", "1200", "5000", "9000", "1030", "12000"],
        itemStyle: {
          color: "#FF3F81",
        },
        lineStyle: {
          color: "#FF3F81",
        },
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
    ],
  }
  const option1 = {
    animation: true,
    animationDuration: 1000, // 动画持续时间（毫秒）
    animationEasing: "cubicOut", // 动画缓动效果
    // 添加 grid 配置来控制图表的边距
    grid: {
      left: "0%", // 左边距，可根据需要调整
      right: "0%", // 右边距
      top: "9%", // 上边距
      bottom: "0%", // 下边距
      containLabel: true, // 确保坐标轴标签不会被截断
    },
    tooltip: {
      trigger: "item", // 触发类型：单个数据项
      backgroundColor: "rgba(255, 255, 255, 0.95)",
      borderColor: "#ddd",
      borderWidth: 1,
      padding: 10,
      textStyle: {
        color: "#333",
        fontSize: 12,
      },
      // 自定义格式化函数（简化版）
      formatter: (param: any) => {
        return `
        <div style="color: rgba(0,0,0,0.45);">01-08</div>
        <div style="display: flex; align-items: center;">
          <img style="width: 10px;height: 10px;margin-right: 5px;" src="${
            param.seriesName === "播放量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng72e7d0ebee61604d7ed1d8269b2c7f202874f0be208ea3d42681a4cd0027af81?noCache=true"
              : param.seriesName === "粉丝量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPngc5961fd693e745d4afffeb0607b0b9f503807cb832e4d8f3ab5cba322b9dfc36?noCache=true"
              : param.seriesName === "评论量"
              ? "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng1c6efa9d2a20041437330faa896d73ada514f1d5d509c1b46d01f15ca0c9f803?noCache=true"
              : "https://lanhu-oss-2537-2.lanhuapp.com/SketchPng81fd1a6069295305f2ff2bcbddec5bad9ba88f62e7bfa56093d56088566bebcc?noCache=true"
          }" />
          <span style="color: rgba(0,0,0,0.45);">${
            param.seriesName
          } <span style="margin-left: 33px;color:#000000;">${
          param.value
        }</span></span>
        </div>
      `
      },
      transitionDuration: 0.2,
    },
    xAxis: {
      type: "category",
      data: xAxisData,
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        color: "rgba(0,0,0,0.45)", // 字体颜色
        fontSize: 12, // 字体大小
        fontFamily: "PingFangSC, PingFang SC", // 字体族
        fontWeight: "normal", // 字体粗细
        interval: "auto", // 标签显示间隔
        // 自定义格式化函数（可选）
        formatter: (value: string, index: number) => {
          // 可以在这里自定义标签显示格式
          return value
        },
      },
      axisLine: {
        show: true, // 是否显示轴线
        lineStyle: {
          color: "rgba(0,0,0,0.15)", // 轴线颜色
          width: 1, // 轴线宽度
          type: "solid", // 轴线样式：solid, dashed, dotted
        },
      },
    },
    yAxis: {
      type: "value",
      color: "#000000", // 字体颜色
      fontSize: 12, // 字体大小
      fontFamily: "PingFangSC, PingFang SC", // 字体族
      fontWeight: "normal", // 字体粗细
      // 自定义格式化函数（可选）
      formatter: (value: number) => {
        if (value >= 1000) {
          return value / 1000 + "k" // 以千为单位显示
        }
        return value.toString()
      },
    },
    series: [
      {
        name: "播放量",
        type: "line",
        data: ["56", "12000", "9000", "6000", "8000", "5000", "15000"],
        itemStyle: {
          color: "#A43AFF",
        },
        lineStyle: {
          color: "#A43AFF",
        },
        animationDelay: (idx: number) => idx * 100,
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
      {
        name: "评论量",
        type: "line",
        data: ["900", "1000", "5000", "6500", "3000", "20", "12000"],
        itemStyle: {
          color: "#FFD33A",
        },
        lineStyle: {
          color: "#FFD33A",
        },
        hoverAnimation: true,
        emphasis: {
          focus: "series",
          lineStyle: { width: 3 },
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
        },
      },
      // {
      //   name: "粉丝量",
      //   type: "line",
      //   data: ["0", "1100", "1300", "6070", "2000", "660", "11000"],
      //   itemStyle: {
      //     color: "#2D84FF",
      //   },
      //   lineStyle: {
      //     color: "#2D84FF",
      //   },
      //   hoverAnimation: true,
      //   emphasis: {
      //     focus: "series",
      //     lineStyle: { width: 3 },
      //     symbol: "circle",
      //     symbolSize: 8,
      //     showSymbol: true,
      //   },
      // },
      // {
      //   name: "喜欢",
      //   type: "line",
      //   data: ["5000", "1200", "1200", "5000", "9000", "1030", "12000"],
      //   itemStyle: {
      //     color: "#FF3F81",
      //   },
      //   lineStyle: {
      //     color: "#FF3F81",
      //   },
      //   hoverAnimation: true,
      //   emphasis: {
      //     focus: "series",
      //     lineStyle: { width: 3 },
      //     symbol: "circle",
      //     symbolSize: 8,
      //     showSymbol: true,
      //   },
      // },
    ],
  }
  const pieOption = {
    title: {
      text: "粉丝比例图",
      textStyle: {
        fontSize: 16,
        color: "rgba(0,0,0,0.85)",
      },
      left: "left",
      top: "top",
    },
    series: [
      {
        type: "pie",
        radius: ["45%", "80%"],
        center: ["50%", "50%"],
        data: [
          { value: 10, name: "X1", itemStyle: { color: "#C05BFA" } },
          { value: 10, name: "Instagram", itemStyle: { color: "#FF6398" } },
          { value: 10, name: "Facebook", itemStyle: { color: "#6380FF" } },
          { value: 10, name: "YouTube", itemStyle: { color: "#FFA15B" } },
          { value: 10, name: "TikTok", itemStyle: { color: "#36D4C9" } },
        ],
        label: {
          show: true,
          position: "inside",
          formatter: "{d}%",
          color: "#fff",
          fontSize: 12,
        },
        labelLine: {
          show: false,
        },
        itemStyle: {
          borderRadius: 0,
        },
        tooltip: {
          trigger: "item",
          formatter: "{b}: {d}%",
        },
      },
    ],
    graphic: [
      {
        type: "text",
        left: "center",
        top: "100",
        style: {
          text: "粉丝总量",
          fontSize: 12,
          fill: "rgba(0,0,0,0.60)",
          textAlign: "center",
          lineHeight: 24,
        },
        z: 10,
      },
      {
        type: "text",
        left: "center",
        top: "123",
        style: {
          text: "14310",
          fontSize: 18,
          fontWeight: "bold",
          fill: "rgba(0,0,0,0.85)",
          textAlign: "center",
          lineHeight: 24,
        },
        z: 10,
      },
    ],
    legend: {
      type: "plain",
      orient: "vertical",
      right: "5%",
      bottom: "5%",
      itemWidth: 12,
      itemHeight: 3,
      // 使用 rich 文本格式化图例
      formatter: function (name) {
        return `{${name}| }`
      },
      textStyle: {
        rich: {
          X1: {
            backgroundColor: {
              image:
                "",
            },
            width: 15,
            height: 14,
            align: "center",
            display: "inline-block",
          },
          Instagram: {
            backgroundColor: {
              image:
                "",
            },
            width: 15,
            height: 14,
            align: "center",
            display: "inline-block",
          },
          Facebook: {
            backgroundColor: {
              image:
                "",
            },
            width: 15,
            height: 14,
            align: "center",
            display: "inline-block",
          },
          YouTube: {
            backgroundColor: {
              image:
                "",
            },
            width: 15,
            height: 14,
            align: "center",
            display: "inline-block",
          },
          TikTok: {
            backgroundColor: {
              image:
                "",
            },
            width: 15,
            height: 14,
            align: "center",
            display: "inline-block",
          },
        },
      },
      data: ["X1", "Instagram", "Facebook", "YouTube", "TikTok"],
      tooltip: {
        show: true,
      },
    },
  }
  myChart.setOption(option)
  myChart1.setOption(option1)
  myPieChart.setOption(pieOption)

  // 使用防抖函数处理resize事件
  const debouncedResizeHandler = () => {
    // 清除之前的定时器
    if (resizeTimer) clearTimeout(resizeTimer)

    // 设置新的定时器，延迟1000ms执行
    resizeTimer = setTimeout(() => {
      if (myChart) {
        myChart.resize()
      }
      if (myChart1) {
        myChart1.resize()
      }
      if (myPieChart) {
        myPieChart.resize()
      }
    }, 500)
  }
  const resizeHandler = debouncedResizeHandler

  // 注册事件监听器
  window.addEventListener("resize", resizeHandler)
  onUnmounted(() => {
    // 清除定时器，防止内存泄漏
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }

    // 移除事件监听器
    window.removeEventListener("resize", resizeHandler)

    // 销毁ECharts实例
    if (myChart) {
      myChart.dispose()
      myChart = null
    }
    if (myChart1) {
      myChart1.dispose()
      myChart1 = null
    }
    if (myPieChart) {
      myPieChart.dispose()
      myPieChart = null
    }
  })
})
</script>

<style>
.el-card {
  background: #ffffff;
  border-radius: 18px;
  padding: 28px 24px;
  margin-bottom: 16px;
}
.el-card__header {
  border-bottom: 0;
  padding: 0;
}
.el-card__body {
  padding: 0;
}
.TabModel {
  margin-top: 30px;
}
.echart-content {
  margin-top: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.echart-chart {
  width: 722px;
}
.shu-line,
.shu-line-261 {
  width: 1px;
  height: 161px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  margin: 0 30px 0 90px;
}
.shu-line-261 {
  height: 261px;
}
.echart-grid {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 285px;
  justify-content: space-between;
}
.echart-grid-row {
  display: flex;
  width: 285px;
  justify-content: space-between; /* 使子元素均匀分布，divider会在中间 */
}
.echart-grid-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 38px;
}
.divider {
  width: 1px;
  height: 54px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  margin-top: 14px;
}

.echart-grid-item-title {
  display: flex;
  align-items: center;
  height: 20px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 20px;
  text-align: left;
  font-style: normal;
}
.echart-grid-item-title img {
  width: 10px;
  margin-right: 8px;
  object-fit: cover;
}
.echart-grid-item-data {
  font-family: AlibabaSans102Dec10, AlibabaSans102Dec10;
  font-weight: 500;
  font-size: 26px;
  color: rgba(0, 0, 0, 0.85);
  line-height: 30px;
  text-align: left;
  margin-left: 18px;
  margin-top: 5px;
}
.echart-grid-item-yesterday {
  height: 20px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 20px;
  text-align: left;
  margin-left: 18px;
  margin-top: 7px;
  margin-right: 7px;
}
.trend-up,
.trend-down {
  height: 18px;
  font-family: AlibabaSans102Dec10, AlibabaSans102Dec10;
  font-weight: 500;
  font-size: 14px;
  color: #ff3f81;
  line-height: 18px;
  text-align: left;
  font-style: normal;
}
.trend-down {
  color: #30a46c;
}
.TabComponent {
  margin-top: 32px;
}
</style>
